package com.mstar.qs.common.log4j;

import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

import com.mstar.qs.common.thread.ThreadUtil;

/**
 * 
 * @author dchen2
 *
 */
public class LogFactory {
	
	public static Logger COMMON_LOGGER=Logger.getLogger(LogFactory.class);

	public static Logger retriveLoger(String name) {
		Logger log = LogManager.exists(name);
		if (log == null)
			return builderLogger(name);
		return log;
	}
	

	public static Logger retriveLoger(Class clazz) {
		return retriveLoger(clazz.getName());
	}

	private static Logger builderLogger(String name) {
		Logger log = Logger.getLogger(name);
		try {
			log.setAdditivity(false);
			log.setLevel(Level.ALL);
			log.getLoggerRepository().setThreshold(Level.INFO);

			PatternLayout l = new PatternLayout();
			l.setConversionPattern("[%p] %d{MM/dd/yyyy HH:mm:ss} %F#%M:%L: %m%n");

			QuoteSpeedDailyRollingFileAppender ap = new QuoteSpeedDailyRollingFileAppender(l, name + ".txt", "'.'yyyy-MM-dd");
			ap.setName(name);
			ap.setLayout(l);
			ap.setImmediateFlush(true);
			ap.setThreshold(Level.INFO);
			ap.setAppend(true);
			ap.setFileSize(2);
			log.addAppender(ap);
		} catch (Throwable e) {
			e.printStackTrace();
		}
		
		return log;
	}
	
	private static String p = "%-15s %50s:%-30s %-15s";;

	public static void printRuntime(Logger log) {
		StackTraceElement e = ThreadUtil.obtainRuntime(4);
		if (e != null)
			printInfo(log, e, null, null);
	}
	
	public static void printRuntime(StackTraceElement e,Logger log,String prefix, String suffix) {
		if (e != null)
			printInfo(log, e, prefix, suffix);
	}
	
	public static void printRuntime(Logger log, String prefix, String suffix) {
		StackTraceElement e = ThreadUtil.obtainRuntime(4);
		if (e != null)
			printInfo(log, e, prefix, suffix);
	}

	private static void printInfo(Logger log, StackTraceElement e, String prefix, String suffix) {
		if (e == null)
			throw new NullPointerException();
		String pre=prefix==null?"":prefix;
		String suf=suffix==null?"":suffix;
		String str=String.format(p, pre,e.getClassName(), e.getMethodName()+":"+e.getLineNumber(), suf);
		if (log != null)
			log.info(str);
		else
			System.out.println(str);
	}
	


}
